import { tableColumnMap } from "../data";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { computed, createVNode, h } from "vue";
import { waitOrderPageDataApi, insuranceShipmentOrderApi, insuranceShipmentOrderPageStatApi } from "@/api/waybillManagement/insurance/placeOrder";
import { passApplyApi, refuseApplyApi, cancelOrderApi, getInsuranceOrderExcelListApi } from "@/api/waybillManagement/insurance/insuranceApproval";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableData, loading, activeKey, pageStat, tableRef, drawerOpts, dialogOpts } = state;
  const selectRows = computed<Array<InsuranceApproval.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    return insuranceShipmentOrderApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return insuranceShipmentOrderPageStatApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, data);
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1", "2", "3"]));
      }
    });
  };
  const getParams = () => {
    const { waybillNumList, bizIdList, addressTypeList, customerIdList, orderNoList, insuranceTypeList, insuranceCompanyIdList, pageNum, pageSize, total } = searchForm;
    const params: Parameters<typeof waitOrderPageDataApi>[0] = {
      waybillNumList: [],
      bizIdList,
      addressTypeList,
      customerIdList,
      orderNoList: [],
      insuranceTypeList,
      insuranceCompanyIdList,
      pageNum,
      pageSize,
      total,
      statusList: activeKey.value === "3" ? [3, 4] : [Number(activeKey.value)]
    };
    if (waybillNumList) {
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }

    if (orderNoList) {
      params.orderNoList = orderNoList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };

  const tableColumn = computed<Array<SuperTable.TableCoulmnItem | SuperTable.NestTableColumnItem>>(() => {
    return tableColumnMap[activeKey.value];
  });

  //驳回
  const refuseApplyHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    Modal.confirm({
      title: "是否驳回？",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        refuseApplyApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };

  //通过
  const passApplyHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    if (selectRows.value.length > 1) {
      Modal.confirm({
        title: h("div", ["是否审核保险单？", h("br"), "保费计算比例默认为0.03%"]),
        icon: createVNode(ExclamationCircleOutlined),
        content: "",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          loading.value = true;
          return passApplyApi({ idList: selectRows.value.map((t: any) => t.id) })
            .then((res: any) => {
              const { code } = res;
              if (code === 200) {
                message.success("操作成功!");
                searchHandle();
              }
            })
            .finally(() => (loading.value = false));
        }
      });
    } else {
      dialogOpts.width = "800px";
      dialogOpts.title = "保险审核";
      dialogOpts.passData = selectRows.value[0];
      dialogOpts.component = "InsuranceReview";
      dialogOpts.visible = true;
    }
  };

  //批量取消
  const cancelOrderHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    Modal.confirm({
      title: "是否取消保险单？",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        cancelOrderApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };

  //单个取消
  const cancelOrderOneHandle = (row: InsuranceApproval.ListRows) => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    Modal.confirm({
      title: "是否取消保险单？",
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        cancelOrderApi([row.id]).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };

  // 查看发票
  const showInvoiceHandle = (row: InsuranceApproval.ListRows) => {
    drawerOpts.width = "1200px";
    drawerOpts.title = "查看发票";
    drawerOpts.type = 1;
    drawerOpts.passData = { id: row.waybillId };
    drawerOpts.component = "ShowInvoice";
    drawerOpts.visible = true;
  };
  //保险审核
  const showInsuranceApprovalHandle = (row: InsuranceApproval.ListRows) => {
    dialogOpts.width = "800px";
    dialogOpts.title = "保险审核";
    dialogOpts.passData = row;
    dialogOpts.component = "InsuranceReview";
    dialogOpts.visible = true;
  };
  //导出
  const exportHandle = () => {
    const params = selectRows.value.length ? { idList: selectRows.value.map(({ id }: { id: string }) => id) } : { ...getParams() };
    loading.value = true;
    return getInsuranceOrderExcelListApi(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) message.success("创建任务成功，请前往导出中心下载！");
        searchHandle();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  return {
    searchHandle,
    getData,
    cancelOrderHandle,
    changeTabHandle,
    pageStateic,
    tableColumn,
    refuseApplyHandle,
    passApplyHandle,
    showInvoiceHandle,
    cancelOrderOneHandle,
    showInsuranceApprovalHandle,
    exportHandle
  };
}
